package com.example.helloworld;

/*
First, a request is sent to the bet_read.php
The returned JSON is then parsed into a hashmap object and displayed.
If nothing is returned, then AddNewBet activity will be launched.
*/

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
 
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
 
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

@SuppressWarnings("javadoc")
public class LoadAllBetsActivity extends ListActivity {
	
	// Progress Dialog
	private ProgressDialog pDialog;

	// JSON Parser object
	JSONParser jParser = new JSONParser();
	
	ArrayList<HashMap<String, String>> betsList;
	
	// URL
	private static String url_root = "http://rsl.lib.fit.edu/android_connect/";
	private static String url_getAllBets = url_root + "bet_all_read.php";
	
	// JSON node names.
	private static final String TAG_SUCCESS = "success";
	private static final String TAG_BETS = "bets";
	private static final String TAG_BETID = "betID";
	private static final String TAG_BETTORID = "bettorID";
	private static final String TAG_ACCEPTORID = "acceptorID";
	private static final String TAG_VALUE = "value";
	
	// JSONArray containing all the bets
	@SuppressWarnings("javadoc")
	JSONArray bets = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.all_bets);
		
		// Hashmap for ListView
		this.betsList = new ArrayList<HashMap<String, String>>();
		
		// Loading bets in Background Thread
		new LoadAllBets().execute();
		
		// Get listview
		ListView lv = getListView();
		
		// On selecting a bet, launch 'Accept Bet' screen.
		lv.setOnItemClickListener(new OnItemClickListener() {
			
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// Gets values from the selected item.
				String betID = ((TextView) view.findViewById(R.id.betID)).getTag().toString();
				
				// Starting new intent.
				// TODO On click, accept the bet.
				Intent in = new Intent(getApplicationContext(), AcceptBetActivity.class);
				
				// Send betID to next activity
				in.putExtra(TAG_BETID, betID);
				
				// Start new activity that expects a response.
				startActivityForResult(in, 100);
			}
		});
	}
	
	// Response from adding a bet.
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		// if result code 100
		if (resultCode == 100){
			// if result is 100
			// user accepted a bet
			// reload the screen
			Intent intent = getIntent();
			finish();
			startActivity(intent);
		}
	}
	
	// Background task to load all bets via HTTP request.
	@SuppressWarnings("javadoc")
	class LoadAllBets extends AsyncTask<String, String, String> {
		
		// Before starting the thread, show progress dialog.
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			LoadAllBetsActivity.this.pDialog = new ProgressDialog(LoadAllBetsActivity.this);
			LoadAllBetsActivity.this.pDialog.setMessage("Loading bets.  Please wait...");
			LoadAllBetsActivity.this.pDialog.setIndeterminate(false);
			LoadAllBetsActivity.this.pDialog.setCancelable(false);
			LoadAllBetsActivity.this.pDialog.show();
		}
		
		// Get all bets via URL.
		@Override
		protected String doInBackground(String... args) {
			// Build parameters.
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			// getting JSON string from URL
			JSONObject json = LoadAllBetsActivity.this.jParser.makeHttpRequest(url_getAllBets, "GET", params);
			
			// Check log for JSON response
			Log.d("All bets: ", json.toString());
			
			try {
				// Check the SUCCESS TAG
				int success = json.getInt(TAG_SUCCESS);
				
				if (success == 1) {
					// bets found
					// Get array of bets
					LoadAllBetsActivity.this.bets = json.getJSONArray(TAG_BETS);
					
					
					
					// loop through all bets
					for(int i = 0; i < LoadAllBetsActivity.this.bets.length(); i++) {
						JSONObject c = LoadAllBetsActivity.this.bets.getJSONObject(i);
						
						// Store each JSON item into a var.
						String betID = c.getString(TAG_BETID);
						String bettorID = c.getString(TAG_BETTORID);
						String acceptorID = c.getString(TAG_ACCEPTORID);
						String value = c.getString(TAG_VALUE);
						
						// create a new HashMap
						HashMap<String, String> map = new HashMap<String, String>();
						
						// add each child to the hashmap
						map.put(TAG_BETID, betID);
						map.put(TAG_BETTORID, bettorID);
						map.put(TAG_ACCEPTORID, acceptorID);
						map.put(TAG_VALUE, value);
						
						// add HashList to ArrayList
						LoadAllBetsActivity.this.betsList.add(map);
					}
				} else {
					// no bets found
					// Launch Add New Bet Activity
					Intent i = new Intent(getApplicationContext(), NewBetActivity.class);
					
					// Close previous activities
					i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(i);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
			return null;
		}
		
		// After background task, dismiss progress dialog.
		@Override
		protected void onPostExecute(String file_url) {
			// dismiss dialog
			LoadAllBetsActivity.this.pDialog.dismiss();
			
			// updating UI from background thread
			runOnUiThread(new Runnable() {
				public void run() {
					// Update parsed JSON data into ListView
					ListAdapter adapter = new SimpleAdapter(
						LoadAllBetsActivity.this, 
						LoadAllBetsActivity.this.betsList, 
						R.layout.list_item, 
						new String[] { TAG_BETID, TAG_BETTORID, TAG_ACCEPTORID, TAG_VALUE }, 
						new int[] { R.id.betID, R.id.bettorID, R.id.value }
					);
					
					// updating listview
					setListAdapter(adapter);
				}
			});
		}
		
	}
}